<template>
  <div class="product-management">
    <a-card class="search-card">
      <a-form :model="searchForm" layout="inline">
        <a-form-item label="商品名称">
          <a-input v-model:value="searchForm.productName" placeholder="请输入商品名称" />
        </a-form-item>
        <a-form-item label="审核状态">
          <a-select v-model:value="searchForm.status" style="width: 120px" placeholder="请选择状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option :value="0">未审核</a-select-option>
            <a-select-option :value="1">审核通过</a-select-option>
            <a-select-option :value="-1">审核不通过</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card>
      <a-table
        :dataSource="filteredProducts"
        :columns="columns"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        rowKey="productId"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'mainImage'">
            <a-image
              :src="record.mainImage"
              :width="60"
              :height="60"
              :preview="false"
            />
          </template>
          <template v-else-if="column.dataIndex === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'deleted'">
            <a-tag :color="record.deleted === 0 ? 'green' : 'red'">
              {{ record.deleted === 0 ? '正常' : '已下架' }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'price'">
            ¥{{ record.price }}
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <div class="action-buttons">
              <a-button
                v-if="record.status === 0"
                type="primary"
                size="small"
                @click="approveProduct(record)"
                style="margin-right: 8px"
              >
                审核通过
              </a-button>
              <a-button
                v-if="record.deleted === 0"
                type="danger"
                size="small"
                @click="handleForceDelete(record)"
              >
                强制下架
              </a-button>
              <span v-if="record.status !== 0 && record.deleted !== 0">-</span>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    

    <!-- 未审核商品提醒模态框 -->
    <a-modal
      v-model:open="unreviewedModalVisible"
      title="提示"
      :footer="null"
      :closable="false"
    >
      <div class="unreviewed-notice">
        <a-alert
          message="您有未审核的商品，请及时处理"
          type="warning"
          show-icon
        />
        <div class="unreviewed-count">
          共 {{ unreviewedCount }} 件商品等待审核
        </div>
        <div class="modal-actions">
          <a-button @click="goToReview">立即处理</a-button>
          <a-button @click="unreviewedModalVisible = false" style="margin-left: 8px">稍后处理</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { getUndeleteProducts, updateProduct, deleteProduct } from '@/api/mall/bizProductController'

// 类型定义
interface Product {
  productId?: number
  sellerUserId?: number
  productName?: string
  price?: number
  status?: number // 0: 未审核, 1: 审核通过, -1: 审核不通过
  mainImage?: string
  createTime?: string
  updateTime?: string
  createBy?: string
  updateBy?: string
  deleted?: number // 0: 正常, 1: 已删除/下架
  stock?: number
  detailImage?: string
  categoryId?: number
  description?: string
  sale?: number
}

// 响应式数据
const loading = ref(false)
const products = ref<Product[]>([])
const unreviewedModalVisible = ref(false)
const unreviewedCount = ref(0)

// 搜索表单
const searchForm = reactive({
  productName: '',
  status: ''
})

// 表格列定义
const columns = [
  {
    title: '商品ID',
    dataIndex: 'productId',
    key: 'productId'
  },
  {
    title: '商品图片',
    dataIndex: 'mainImage',
    key: 'mainImage'
  },
  {
    title: '商品名称',
    dataIndex: 'productName',
    key: 'productName'
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price'
  },
  {
    title: '库存',
    dataIndex: 'stock',
    key: 'stock'
  },
  {
    title: '审核状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '商品状态',
    dataIndex: 'deleted',
    key: 'deleted'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
})

// 计算属性：过滤后的商品列表
const filteredProducts = computed(() => {
  let result = [...products.value]
  
  // 根据商品名称过滤
  if (searchForm.productName) {
    result = result.filter(product => 
      product.productName?.includes(searchForm.productName)
    )
  }
  
  // 根据审核状态过滤
  if (searchForm.status !== '') {
    const statusValue = parseInt(searchForm.status as string)
    result = result.filter(product => product.status === statusValue)
  }
  
  // 更新分页总数
  pagination.total = result.length
  
  // 分页处理
  const start = (pagination.current - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return result.slice(start, end)
})

// 获取商品列表
const fetchProducts = async () => {
  try {
    loading.value = true
    const res = await getUndeleteProducts()
    
    if (res.code === '00000') {
      products.value = res.data || []
      pagination.total = products.value.length
      
      // 计算未审核商品数量
      unreviewedCount.value = products.value.filter(
        product => product.status === 0
      ).length
      
      // 如果有未审核商品，显示提醒模态框
      if (unreviewedCount.value > 0) {
        unreviewedModalVisible.value = true
      }
    } else {
      message.error(res.msg || '获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    message.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 处理表格分页、排序、筛选变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}

// 查询
const handleSearch = () => {
  pagination.current = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.productName = ''
  searchForm.status = ''
  pagination.current = 1
}

// 显示审核模态框
const showAuditModal = (product: Product) => {
  currentProduct.value = { ...product }
  auditForm.status = 1
  auditForm.remark = ''
  auditModalVisible.value = true
}

// 审核通过商品
const approveProduct = async (product: Product) => {
  Modal.confirm({
    title: '确认审核通过',
    content: `确定要审核通过商品 "${product.productName}" 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        loading.value = true
        const productToUpdate = {
          ...product,
          status: 1 // 审核通过
        }
        
        const res = await updateProduct(productToUpdate)
        
        if (res.code === '00000') {
          message.success('审核通过成功')
          await fetchProducts()
        } else {
          message.error(res.msg || '审核失败')
        }
      } catch (error) {
        console.error('审核失败:', error)
        message.error('审核失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 强制下架商品
const handleForceDelete = (product: Product) => {
  Modal.confirm({
    title: '确认强制下架',
    content: `确定要强制下架商品 "${product.productName}" 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        loading.value = true
        // 使用delete方法强制下架商品
        const res = await deleteProduct({ id: product.productId })
        
        if (res.code === '00000') {
          message.success('强制下架成功')
          await fetchProducts()
        } else {
          message.error(res.msg || '强制下架失败')
        }
      } catch (error) {
        console.error('强制下架失败:', error)
        message.error('强制下架失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 立即处理未审核商品
const goToReview = () => {
  unreviewedModalVisible.value = false
  // 设置搜索条件为未审核
  searchForm.status = '0'
  pagination.current = 1
}

// 获取状态文本
const getStatusText = (status: number | undefined) => {
  switch (status) {
    case 0: return '未审核'
    case 1: return '审核通过'
    case -1: return '审核不通过'
    default: return '未知状态'
  }
}

// 获取状态颜色
const getStatusColor = (status: number | undefined) => {
  switch (status) {
    case 0: return 'orange'
    case 1: return 'green'
    case -1: return 'red'
    default: return 'default'
  }
}

// 组件挂载时获取商品列表
onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.product-management {
  padding: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.action-buttons {
  display: flex;
}

.unreviewed-notice {
  text-align: center;
}

.unreviewed-count {
  margin: 16px 0;
  font-size: 16px;
  font-weight: bold;
}

.modal-actions {
  margin-top: 24px;
}

.audit-product-info {
  max-height: 400px;
  overflow-y: auto;
}
</style>